package com.ruoyi.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.InviteCode;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.T16;
import com.ruoyi.service.IT16Service;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 二维码记录Controller
 *
 * @author ruoyi
 * @date 2024-08-07
 */
@RestController
@RequestMapping("/system/T16")
public class T16Controller extends BaseController
{
    private static final String REGISTER_URL = "https://www.baidu.com";
    public  static final String INVITE_CODE_PREFIXCode = "Invite_Code";
    @Autowired
    private IT16Service t16Service;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询二维码记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:T16:list')")
    @GetMapping("/list")
    @ApiOperation("列表")
    public TableDataInfo list(T16 t16)
    {
        startPage();
        List<T16> list = t16Service.selectT16List(t16);
        return getDataTable(list);
    }

    /**
     * 导出二维码记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:T16:export')")
    @Log(title = "二维码记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, T16 t16)
    {
        List<T16> list = t16Service.selectT16List(t16);
        ExcelUtil<T16> util = new ExcelUtil<T16>(T16.class);
        util.exportExcel(response, list, "二维码记录数据");
    }

    /**
     * 获取二维码记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:T16:query')")
    @GetMapping(value = "/{F1601}")
    public AjaxResult getInfo(@PathVariable("F1601") Long F1601)
    {
        return success(t16Service.selectT16ByF1601(F1601));
    }

    /**
     * 新增二维码记录
     */
    @PreAuthorize("@ss.hasPermi('system:T16:add')")
    @Log(title = "二维码记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody T16 t16)
    {
        return toAjax(t16Service.insertT16(t16));
    }

    /**
     * 修改二维码记录
     */
    @PreAuthorize("@ss.hasPermi('system:T16:edit')")
    @Log(title = "二维码记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody T16 t16)
    {
        return toAjax(t16Service.updateT16(t16));
    }

    /**
     * 删除二维码记录
     */
    @PreAuthorize("@ss.hasPermi('system:T16:remove')")
    @Log(title = "二维码记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{F1601s}")
    public AjaxResult remove(@PathVariable Long[] F1601s)
    {
        return toAjax(t16Service.deleteT16ByF1601s(F1601s));
    }
    @ApiOperation("二维码生成")
    @PostMapping("/QRCode")
    public void generateQRCode(HttpServletRequest request, @RequestParam("time")String timeStr,HttpServletResponse response) throws  IOException, WriterException{
        try {
            // 从请求中获取登录用户信息
            LoginUser loginUser = tokenService.getLoginUser(request); // 确保tokenService和getLoginUser方法存在
            Long userId = loginUser.getUserId();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 设置时区为 UTC
            Date time = sdf.parse(timeStr);

            int  expireSeconds = (int) ((time.getTime() - System.currentTimeMillis()) / 1000);

            String invitcode = InviteCode.getInviteCode();
            String key = INVITE_CODE_PREFIXCode + invitcode;
            redisCache.setCacheObject(key,invitcode,expireSeconds,TimeUnit.SECONDS);
            // 生成二维码内容
            String content =
//                    REGISTER_URL +
                            "?userId=" + userId + "&time=" + timeStr + "&inviteCode=" + invitcode;
            // 使用ZXing库生成二维码
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200);
            BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            // 将BufferedImage转换为byte数组
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(qrCodeImage, "png", bos);

            // 将byte数组转换为二进制格式的响应体
            byte[] qrCodeBytes = bos.toByteArray();

            AjaxResult result = AjaxResult.success("二维码生成成功", qrCodeBytes);

//             设置响应头信息
            response.setContentType("image/png");
//             直接写入响应体，注意这里不应该同时返回AjaxResult对象给前端
            response.getOutputStream().write(qrCodeBytes);

            // 因为已经写入了响应体，这里返回null或者result都可以，取决于您的具体需求
//            return AjaxResult.success(qrCodeBytes);
        } catch (IOException e) {
            e.printStackTrace();
            // 返回错误信息的AjaxResult对象
//            return AjaxResult.error("二维码生成失败，IO异常");
        } catch (WriterException | ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("二维码生成失败，Writer异常");
            // 返回错误信息的AjaxResult对象
//            return AjaxResult.error("二维码生成失败，Writer异常");
        }
    }
    @GetMapping("/verify-invite-code")
    @ApiOperation("二维码验证")
    public ResponseEntity<?> verifyInviteCode(@RequestParam("inviteCode") String inviteCode) {
        try {
            // 从Redis中获取邀请码信息
            String storedInviteCode = (String) redisTemplate.opsForValue().get(INVITE_CODE_PREFIXCode + inviteCode);

            // 检查邀请码是否存在
            if (StringUtils.isNotBlank(storedInviteCode)) {
                // 邀请码有效，进行进一步的业务逻辑处理
                // 例如，重定向到注册页面或返回注册页面的URL
                return ResponseEntity.ok().body("邀请码验证成功，即将跳转到注册页面");
            } else {
                // 邀请码不存在或已过期
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无效的邀请码");
            }
        } catch (Exception e) {
            // 处理异常情况
            return ResponseEntity.status(HttpStatus.ERROR).body("服务器错误");
        }
    }
}
